<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2024/2/28
 * Time: 14:21
 */

namespace app\api\controller;

use app\api\model\ShopCar;
use app\api\model\Goods;
use app\api\model\GoodsSpec;
use app\api\model\GoodsPackaging;
use app\api\model\UUser;
use http\Exception;
use think\Db;
use app\api\model\Order AS OrderModel;
use app\api\model\OrderInfo;

class Order extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 确认订单展示页
     * sc_ids           购物车ID，从购物车提交订单时传该值
     * goods_id         商品ID，从商品详情提交订单时传该值
     * packaging_id     包装ID，从商品详情提交订单时传该值
     * spec_id          规格ID，从商品详情提交订单时传该值
     * goods_quantity   数量，从商品详情提交订单时传该值
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showConfirmOrder(){
        $sc_ids = input('sc_ids');
        $goods_id = input('goods_id');
        $packaging_id = input('packaging_id');
        $spec_id = input('spec_id');
        $goods_quantity = input('goods_quantity');

        if($sc_ids){ // 购物车
            $where = ['sc_id' => ['IN', $sc_ids]];
            $field = 'goods_name_en, goods_name_es, goods_name_tp, goods_thumb, packaging_name, spec_value, 
            spec_price, spec_cu_price, sc_number, goods_status';
            $data = ShopCar::selectJoinData($where, $field)->toArray();

            $flag = ['status' => 200, 'msg' => '']; // 商品状态标记
            $totalPrice = 0;

            if($data){
                foreach ($data as $k => $v){
                    // 商品状态异常
                    if($v['goods_status'] != 1){
                        if($this->lanType == 0){
                            $msg = $this->lanMsg->goodsStatusErr[0] . '--' . $v['goods_name_en'];
                        }elseif ($this->lanType == 1){
                            $msg = $this->lanMsg->goodsStatusErr[1] . '--' . $v['goods_name_es'];
                        }else{
                            $msg = $this->lanMsg->goodsStatusErr[2] . '--' . $v['goods_name_tp'];
                        }
                        $flag['status'] = 0;
                        $flag['msg'] = $msg;
                        break;
                    }

                    // 总价
                    $totalPrice += $v['sc_number'] * $v['spec_cu_price'];
                    // 图片
                    if($v['goods_thumb']){
                        $data[$k]['goods_thumb'] = http_type() . $v['goods_thumb'];
                    }

                }
                if($flag['status'] == 0) return json($flag);
            }
        }else{ // 商品详情
            if(!$goods_id) return json(['status' => 0, 'msg' => $this->lanMsg->goodsIDErr[$this->lanType]]);
            if(!$packaging_id) return json(['status' => 0, 'msg' => $this->lanMsg->packagingIDErr[$this->lanType]]);
            if(!$spec_id) return json(['status' => 0, 'msg' => $this->lanMsg->specIDErr[$this->lanType]]);
            if(!$goods_quantity) return json(['status' => 0, 'msg' => $this->lanMsg->numberMustHave[$this->lanType]]);

            // 商品
            $goodsWhere = ['goods_id' => $goods_id];
            $goodsField = 'goods_name_en, goods_name_es, goods_name_tp, goods_thumb';
            $goods = Goods::findData($goodsWhere, $goodsField)->toArray();
            // 包装
            $goods['packaging_name'] = GoodsPackaging::get($packaging_id)['packaging_name'];
            // 规格
            $spec = GoodsSpec::get($spec_id);
            $goods['spec_value'] = $spec['spec_value'];
            // 价格
            $goods['spec_price'] = $spec['spec_price'];
            $goods['spec_cu_price'] = $spec['spec_cu_price'];
            $data[] = $goods;
            // 总价
            $totalPrice = $goods_quantity * $goods['spec_cu_price'];
        }

        return json(['status' => 200, 'msg' => $data, 'totalPrice' => $totalPrice]);
    }

    /**
     * 商品详情页提交订单
     * addr_id          地址ID
     * goods_id         商品ID
     * packaging_id     包装ID
     * spec_id          规格值ID
     * goods_quantity   数量
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsCommitOrder(){
        $addr_id = input('addr_id');
        $goods_id = input('goods_id');
        $packaging_id = input('packaging_id');
        $spec_id = input('spec_id');
        $goods_quantity = input('goods_quantity');

        if(!$addr_id) return json(['status' => 0, 'msg' => $this->lanMsg->chooseAddress[$this->lanType]]);
        if(!$goods_id) return json(['status' => 0, 'msg' => $this->lanMsg->goodsIDErr[$this->lanType]]);
        if(!$packaging_id) return json(['status' => 0, 'msg' => $this->lanMsg->packagingIDErr[$this->lanType]]);
        if(!$spec_id) return json(['status' => 0, 'msg' => $this->lanMsg->specIDErr[$this->lanType]]);
        if(!$goods_quantity) return json(['status' => 0, 'msg' => $this->lanMsg->numberMustHave[$this->lanType]]);

        $goods = Goods::findData(['goods_id' => $goods_id], 'goods_status');
        if($goods['goods_status'] != 1) return json(['status' => 0, 'msg' => $this->lanMsg->goodsStatusErr[$this->lanType]]);

        $goods_number = date('YmdHis') . rand(0000, 9999);

        $spec = GoodsSpec::get($spec_id);
        $totalPrice = $goods_quantity * $spec['spec_cu_price'];

        $create = [
            'order_number' => $goods_number,
            'order_quantity' => $goods_quantity,
            'order_total_price' => $totalPrice,
            'order_user_id' => $this->user_id,
            'order_addr_id' => $addr_id,
            'order_time' => initTime()
        ];
        $info = [
            'of_user_id' => $this->user_id,
            'of_goods_id' => $goods_id,
            'of_packaging_id' => $packaging_id,
            'of_spec_id' => $spec_id,
            'of_quantity' => $goods_quantity,
            'of_price' => $spec['spec_cu_price'],
            'of_total_price' => $totalPrice
        ];

        Db::startTrans();
        try{
            // 订单列表
            OrderModel::create($create);
            $order_id = OrderModel::getLastInsId();

            // 订单详情
            $info['of_order_id'] = $order_id;
            OrderInfo::create($info);

            Db::commit();
            return json(['status' => 200, 'msg' => $this->lanMsg->doSuccess[$this->lanType], 'order_id' => $order_id]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 购物车提交订单
     * sc_ids     购物车ID，逗号隔开
     * addr_id    地址收货ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopCarCommitOrder(){
        $sc_ids = input('sc_ids');
        $addr_id = input('addr_id');

        if(!$sc_ids) return json(['status' => 0, 'msg' => $this->lanMsg->chooseCommitShopCar[$this->lanType]]);
        if(!$addr_id) return json(['status' => 0, 'msg' => $this->lanMsg->chooseAddress[$this->lanType]]);

        $where = ['sc_id' => ['IN', $sc_ids]];
        $field = 'sc_goods_id, sc_packaging_id, sc_spec_id, sc_number, spec_price, spec_cu_price, goods_status';
        $shopCar = ShopCar::selectJoinData($where, $field, 1, 3);
        if(!$shopCar) return json(['status' => 0, 'msg' => $this->lanMsg->requireShopCarCommit[$this->lanType]]);

        $flag = ['status' => 200, 'msg' => '']; // 商品状态标记
        $totalPrice = 0; // 订单总价
        $totalQuantity = 0; // 订单总数量
        $infoAll = [];

        foreach ($shopCar as $k => $v){
            // 商品状态异常
            if($v['goods_status'] != 1){
                if($this->lanType == 0){
                    $msg = $this->lanMsg->goodsStatusErr[0] . '--' . $v['goods_name_en'];
                }elseif ($this->lanType == 1){
                    $msg = $this->lanMsg->goodsStatusErr[1] . '--' . $v['goods_name_es'];
                }else{
                    $msg = $this->lanMsg->goodsStatusErr[2] . '--' . $v['goods_name_tp'];
                }
                $flag['status'] = 0;
                $flag['msg'] = $msg;
                break;
            }

            // 总价
            $totalPrice += $v['sc_number'] * $v['spec_cu_price'];
            // 总量
            $totalQuantity += $v['sc_number'];
            // 商品详情数组
            $infoAll[$k] = [
                'of_user_id' => $this->user_id,
                'of_goods_id' => $v['sc_goods_id'],
                'of_packaging_id' => $v['sc_packaging_id'],
                'of_spec_id' => $v['sc_spec_id'],
                'of_quantity' => $v['sc_number'],
                'of_price' => $v['spec_cu_price'],
                'of_total_price' => $v['sc_number'] * $v['spec_cu_price']
            ];

        }
        if($flag['status'] == 0) return json($flag);

        $goods_number = date('YmdHis') . rand(0000, 9999);

        $create = [
            'order_number' => $goods_number,
            'order_quantity' => $totalQuantity,
            'order_total_price' => $totalPrice,
            'order_user_id' => $this->user_id,
            'order_addr_id' => $addr_id,
            'order_time' => initTime()
        ];

        Db::startTrans();
        try{
            // 订单表
            OrderModel::create($create);
            $order_id = OrderModel::getLastInsId();

            // 订单详情
            if($infoAll){
                foreach ($infoAll as $ki => $vi){
                    $infoAll[$ki]['of_order_id'] = $order_id;
                }
                OrderInfo::insertAllData($infoAll);
            }

            // 删除购物车
            ShopCar::delData(['sc_id' => ['IN', $sc_ids]]);

            Db::commit();
            return json(['status' => 200, 'msg' => $this->lanMsg->doSuccess[$this->lanType], 'order_id' => $order_id]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 订单列表
     * status   状态 0.全部  1.待确认  2.待付款  3.待发货  4.待收货  5.已完成
     * page     页码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderList(){
        $status = input('status') ? input('status') : 0; // 0.全部  1.待确认  2.待付款  3.待发货  4.待收货  5.已完成
        $page = input('page') ? input('page') : 1;

        $user = UUser::findData(['user_id' => $this->user_id], 'user_auth, user_leader, user_f_id');
        if($user['user_auth'] == 2){
            $where['order_user_id'] = $this->user_id;
        }else{
            if($user['user_leader'] == 1){
                $where['order_user_id'] = $this->user_id;
            }else{
                // 我的下级/员工
                $lowUser = UUser::findData(['user_f_id' => $this->user_id], 'user_id');
                $where['order_user_id'] = [['=', $lowUser['user_id']], ['=', $this->user_id], 'OR'];
            }
        }

        if($status != 0){
            $where['order_status'] = $status;
        }

        $field = 'order_id, order_number, order_total_price, order_status, order_time, order_addr_id';
        $order = OrderModel::selectData($where, $field, $page)->toArray();

        if($order){
            $order_ids = array_column($order, 'order_id');
            $whereInfo['of_order_id'] = ['IN', $order_ids];
            $fieldInfo = 'of_id, of_quantity, of_order_id, spec_value, packaging_name, goods_name_en, goods_name_es, 
            goods_name_tp, goods_thumb, of_goods_id, of_packaging_id, of_spec_id, of_goods_id, of_price';
            $orderInfo = OrderInfo::selectJoinData($whereInfo, $fieldInfo)->toArray();
            if($orderInfo){
                foreach ($orderInfo as $ki => $vi){
                    if($vi['goods_thumb']){
                        $orderInfo[$ki]['goods_thumb'] = http_type() . $vi['goods_thumb'];
                    }
                }
            }
            foreach ($order as $ko => $vo){
                $orderGoods = array();
                if($orderInfo){
                    foreach ($orderInfo as $ki => $vi){
                        if($vi['of_order_id'] == $vo['order_id']){
                            $orderGoods[] = $vi;
                        }
                    }
                }
                $order[$ko]['orderGoods'] = $orderGoods;
            }
            $count = OrderModel::countData($where);
            return json(['status' => 200, 'msg' => $order, 'count' => $count]);
        }else{
            return json(['status' => 200, 'msg' => [], 'count' => 0]);
        }
    }

    /**
     * 确认订单
     * order_id    订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sureOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => $this->lanMsg->orderIDErr[$this->lanType]]);

        $order = OrderModel::findData(['order_id' => $order_id], 'order_status, order_user_id');
        if($order['order_status'] != 1) return json(['status' => 0, 'msg' => $this->lanMsg->orderStatusErr[$this->lanType]]);

        $user = UUser::findData(['user_id' => $this->user_id]);
        if($user['user_leader'] == 1){
            return json(['status' => 0, 'msg' => $this->lanMsg->noAuth[$this->lanType]]);
        }else{
            $myLower = UUser::findData(['user_f_id' => $this->user_id]); // 我的下级
            if($myLower['user_id'] != $order['order_user_id']){
                return json(['status' => 0, 'msg' => $this->lanMsg->canNotDo[$this->lanType]]);
            }
        }
        $update = [
            'order_status' => 2,
            'order_verify_user_id' => $this->user_id,
            'order_verify_time' => initTime()
        ];

        $res = OrderModel::update($update, ['order_id' => $order_id]);
        if($res){
            return json(['status' => 200, 'msg' => $this->lanMsg->doSuccess[$this->lanType]]);
        }else{
            return json(['status' => 0, 'msg' => $this->lanMsg->systemErr[$this->lanType]]);
        }

    }

    /**
     * 收货
     * order_id    订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function overOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => $this->lanMsg->orderIDErr[$this->lanType]]);

        $order = OrderModel::findData(['order_id' => $order_id], 'order_status');
        if($order['order_status'] != 4) return json(['status' => 0, 'msg' => $this->lanMsg->orderStatusErr[$this->lanType]]);

        $update = [
            'order_status' => 5,
            'order_over_time' => initTime()
        ];

        $res = OrderModel::update($update, ['order_id' => $order_id]);
        if($res){
            return json(['status' => 200, 'msg' => $this->lanMsg->doSuccess[$this->lanType]]);
        }else{
            return json(['status' => 0, 'msg' => $this->lanMsg->systemErr[$this->lanType]]);
        }
    }

    /**
     * 取消订单
     * order_id    订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancelOrder(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => $this->lanMsg->orderIDErr[$this->lanType]]);

        $order = OrderModel::findData(['order_id' => $order_id], 'order_status');
        if($order['order_status'] > 2) return json(['status' => 0, 'msg' => $this->lanMsg->orderStatusErr[$this->lanType]]);

        $update = [
            'order_status' => 6,
            'order_cancel_time' => initTime()
        ];

        $res = OrderModel::update($update, ['order_id' => $order_id]);
        if($res){
            return json(['status' => 200, 'msg' => $this->lanMsg->doSuccess[$this->lanType]]);
        }else{
            return json(['status' => 0, 'msg' => $this->lanMsg->systemErr[$this->lanType]]);
        }
    }

    /**
     * 订单详情
     * order_id   订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderDetail(){
        $order_id = input('order_id');

        if(!$order_id) return json(['status' => 0, 'msg' => $this->lanMsg->orderIDErr[$this->lanType]]);

        $where['order_id'] = $order_id;
        $field = 'order_id, order_number, order_total_price, order_time, order_wuLiu_company, order_wuLiu_code, 
        order_wuLiu_desc, order_status, addr_xing, addr_name, addr_phone, addr_postal, addr_company, addr_address';
        $order = OrderModel::findJoinData($where, $field);

        $whereInfo['of_order_id'] = $order_id;
        $fieldInfo = 'of_id, of_quantity, of_order_id, spec_value, packaging_name, goods_name_en, goods_name_es, 
            goods_name_tp, goods_thumb, of_price, of_goods_id';
        $orderInfo = OrderInfo::selectJoinData($whereInfo, $fieldInfo)->toArray();

        foreach ($orderInfo as $k => $v){
            if($v['goods_thumb']){
                $orderInfo[$k]['goods_thumb'] = http_type() . $v['goods_thumb'];
            }
        }

        $order['orderGoods'] = $orderInfo;

        return json(['status' => 200, 'msg' => $order]);
    }
}